<template>
	<view class="t-index-address">
		<scroll-view class="t-index-address__scroll-view" :scroll-into-view="scrollview" :scroll-y="true"
			:enable-flex="true">
			<view :id="group.initial" v-for="group in cityList" :key="group.initial">
				<view class="t-index-address__anchor">
					<text>{{ group.initial }}</text>
				</view>
				<view class="t-index-address__list">
					<view class="t-index-address__cell" v-for="(city, index) in group.list" :key="index"
						@click="$emit('select', city)">
						<text>{{ city.name }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="t-index-address__sidebar">
			<view class="t-index-address__index" v-for="group in cityList" :key="group.initial"
				@touchstart.stop.prevent="onTouchMove(group.initial)" @touchend.stop.prevent="onTouchStop"
				@touchcancel.stop.prevent="onTouchStop">
				<span>{{ group.initial }}</span>
			</view>
		</view>
		<view class="t-index-address__alert" v-if="touchmove">
			<text>{{ activeIndex }}</text>
		</view>
	</view>
</template>

<script>
	import pinyin from 'js-pinyin'
	export default {
		data() {
			return {
				scrollview: "A",
				cityList: [],
				activeIndex: "A",
				touchmove: false,
			};
		},
		watch: {
			activeIndex(value) {
				this.scrollview = value;
			},
		},
		methods: {
			initCityList() {
				let data = {
					language:'zh_CN'
				}
				getApp().globalData.api.getAllRegion(data, result => {
					// let arr = this.sort(result, 'code');
					// let arr = this.sortByFirstLetter(result, 'code');
					// let arr1 = this.pySegSort(result);
					// this.cityList = arr1
					
					let arr = result.map((item)=>{
						return{
							letter:pinyin.getFullChars(item.name),
							...item
						}
					})
					let arr1 = this.sort(arr, 'letter')
					this.cityList = arr1
					console.log('分类后的所有地区',arr); 
				})
			},
			onTouchMove(index) {
				this.activeIndex = index;
				this.touchmove = true;
			},
			onTouchStop() {
				this.touchmove = false;
			},
			//按拼音首字母分类
			pySegSort(arr){
			    if (!String.prototype.localeCompare) return null
			    let letters = 'abcdefghjklmnopqrstwxyz'.split('')
			    let zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀'.split('')
			    let segs = []
			    letters.map((item, i) => {
			        let cur = { initial: item.toUpperCase(), list: [] }
					console.log('aaaaaaaaaaa===',item,i,zh[i]);
			        arr.map((arrItem) => {
			            if(arrItem.name.localeCompare(zh[i])>=0&&arrItem.name.localeCompare(zh[i+1])<0){
			                cur.list.push(arrItem)
			            }         
			        })
			        if (cur.list.length) {   
			            cur.list.sort(function(a, b) {
			                return a.name.localeCompare(b.name, 'zh')
			            })
			            segs.push(cur)   
			        }
			    })
			    return segs
			},
			sortByFirstLetter(origin) {
			    // 将目标数据进行排序
			    origin = origin.sort((pre, next) => Pinyin.getFullChars(pre).localeCompare(Pinyin.getFullChars(next)))
			    const newArr = []
			    origin.map(item => {
			        // 取首字母
			        const key = Pinyin.getFullChars(item).charAt(0)
			        const index = newArr.findIndex(subItem => subItem.key === key)
			        if (index < 0) {
			            newArr.push({
			                key: key,
			                list: [item]
			            })
			        } else {
			            newArr[index].list.push(item)
			        }
			    })
			    return newArr
			},
			sort (data, field) {
			    var letter_reg = /^[A-Z]$/;
			    var list = new Array();
				let testArr = []
			    for (var i = 0; i < data.length; i++) {
			        // 添加 # 分组，用来 存放 首字母不能 转为 大写英文的 数据
			        list[' '] = new Array();
			        // 首字母 转 大写英文
			        let letter = (data[i][field]).substr(0, 1).toUpperCase();
			        // 是否 大写 英文 字母
			        if (!letter_reg.test(letter)) {
			            letter = ' ';
			        }
			        // 创建 字母 分组
			        if (!(letter in list)) {
			            list[letter] = new Array();
			        }
			        // 字母 分组 添加 数据
			        list[letter].push(data[i]);
			    }
			    // 转换 格式 进行 排序；
			    var resault = new Array();
			    for (var key in list) {
			        resault.push({
			            letter: key,
			            list: list[key]
			        });
			    }
			    resault.sort(function (x, y) {
			        return x.letter.charCodeAt(0) - y.letter.charCodeAt(0);
			    });
			    // # 号分组 放最后
			    var last_arr = resault[0];
			    resault.splice(0, 1);
			    resault.push(last_arr);
			
			    // 转换 数据 格式
			    var json_sort = {}
			    for (var i = 0; i < resault.length; i++) {
			        json_sort[resault[i].letter] = resault[i].list;
			    }
				for (let key in json_sort) {
					testArr.push({
						initial:key,
						list:json_sort[key]
					})
				}
			    // return json_sort;
				return testArr;
			}
		},
		mounted() {
			this.initCityList();
		},
	};
</script>

<style lang="scss" scoped>
	.t-index-address {
		height: 100%;

		&__scroll-view {
			width: 100%;
			height: 100%;
			max-height: 100vh;
		}

		&__anchor {
			padding: 15rpx 30rpx;
			width: 100%;
			font-size: 28rpx;
			font-weight: 500;
			color: #606266;
			background-color: rgb(245, 245, 245);
		}

		&__list {
			padding: 0 70rpx 0 30rpx;
		}

		&__cell {
			height: 100rpx;
			line-height: 100rpx;
			border-bottom: 1rpx solid #f2f2f2;

			&:last-child {
				border: none;
			}
		}

		&__sidebar {
			position: fixed;
			top: 50%;
			right: 0;
			transform: translateY(-50%);
			z-index: 99;
		}

		&__index {
			padding: 10rpx 20rpx;
			font-size: 22rpx;
			font-weight: 500;
			line-height: 1;
		}

		&__alert {
			position: fixed;
			top: 50%;
			right: 90rpx;
			z-index: 99;
			margin-top: -60rpx;
			width: 120rpx;
			height: 120rpx;
			font-size: 50rpx;
			color: #fff;
			border-radius: 24rpx;
			background-color: rgba(0, 0, 0, 0.5);
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
</style>
